<template>
  <div>
    <h3>业务管理表格</h3>
    <el-input
        placeholder="请输入业务名称"
        v-model="searchQuery"
        style="width: 200px; margin-right: 10px;"
        clearable
        @clear="fetchOperations"
    />
    <el-button type="primary" @click="searchOperations">搜索</el-button>
    <el-button type="primary" @click="openDialog">添加业务</el-button>
    <el-table :data="operations" style="width: 100%; margin-top: 20px;">
      <!-- 表格列定义 -->
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="customerName" label="客户名称" width="180"></el-table-column>
      <el-table-column prop="name" label="业务名称" width="180"></el-table-column>
      <el-table-column prop="state" label="业务状态" width="180"></el-table-column>
      <el-table-column prop="area" label="区域" width="180"></el-table-column>
      <el-table-column prop="goods" label="商品" width="180"></el-table-column>
      <el-table-column prop="workorderId" label="工单ID" width="180"></el-table-column>
      <el-table-column prop="workorderType" label="工单类型" width="180"></el-table-column>
      <el-table-column prop="workorderReceiveDate" label="接单日期" width="180"></el-table-column>
      <el-table-column prop="workorderReturnDate" label="回单日期" width="180"></el-table-column>
      <el-table-column prop="workorderState" label="工单状态" width="180"></el-table-column>
      <el-table-column prop="fillDate" label="填写时间" width="180"></el-table-column>
      <el-table-column prop="operator" label="操作员" width="180"></el-table-column>
      <el-table-column prop="dataState" label="数据状态" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="small" @click="editOperation(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOperation(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="isEdit ? '编辑业务' : '添加业务'" v-model="dialogVisible">
      <el-form :model="newOperation" :rules="rules" ref="operationForm">
        <!-- 表单项定义 -->
        <el-form-item label="客户名称" :label-width="formLabelWidth" prop="customerName">
          <el-select v-model="newOperation.customerName" placeholder="请选择客户">
            <el-option v-for="customer in customers" :key="customer.id" :label="customer.name" :value="customer.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="newOperation.name"></el-input>
        </el-form-item>
        <el-form-item label="业务状态" :label-width="formLabelWidth" prop="state">
          <el-select v-model="newOperation.state" placeholder="请选择业务状态">
            <el-option label="正式业务" value="正式业务"></el-option>
            <el-option label="试用业务" value="试用业务"></el-option>
            <el-option label="拆机业务" value="拆机业务"></el-option>
            <el-option label="试用结束业务" value="试用结束业务"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域" :label-width="formLabelWidth" prop="area">
          <el-select v-model="newOperation.area" placeholder="请选择区域">
            <el-option v-for="area in areas" :key="area.id" :label="area.name" :value="area.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品" :label-width="formLabelWidth" prop="goods">
          <el-input v-model="newOperation.goods"></el-input>
        </el-form-item>
        <el-form-item label="工单ID" :label-width="formLabelWidth" prop="workorderId">
          <el-input v-model="newOperation.workorderId"></el-input>
        </el-form-item>
        <el-form-item label="工单类型" :label-width="formLabelWidth" prop="workorderType">
          <el-input v-model="newOperation.workorderType"></el-input>
        </el-form-item>
        <el-form-item label="接单日期" :label-width="formLabelWidth" prop="workorderReceiveDate">
          <el-date-picker v-model="newOperation.workorderReceiveDate" type="date" placeholder="选择接单日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="回单日期" :label-width="formLabelWidth" prop="workorderReturnDate">
          <el-date-picker v-model="newOperation.workorderReturnDate" type="date" placeholder="选择回单日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="工单状态" :label-width="formLabelWidth" prop="workorderState">
          <el-select v-model="newOperation.workorderState" placeholder="请选择工单状态">
            <el-option label="未派单" value="未派单"></el-option>
            <el-option label="已派单" value="已派单"></el-option>
            <el-option label="已收单" value="已收单"></el-option>
            <el-option label="已回单" value="已回单"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="填写时间" :label-width="formLabelWidth" prop="fillDate">
          <el-date-picker v-model="newOperation.fillDate" type="date" placeholder="选择填写时间"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrUpdateOperation">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      operations: [],
      customers: [],
      areas: [],
      dialogVisible: false,
      isEdit: false,
      searchQuery: '',
      newOperation: {
        customerName: '',
        name: '',
        state: '',
        area: '',
        goods: '',
        workorderId: '',
        workorderType: '',
        workorderReceiveDate: '',
        workorderReturnDate: '',
        workorderState: '',
        fillDate: '',
        operator: '',
        dataState: ''
      },
      formLabelWidth: '120px',
      rules: {
        customerName: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
        name: [{ required: true, message: '请输入业务名称', trigger: 'blur' }],
        state: [{ required: true, message: '请选择业务状态', trigger: 'change' }],
        area: [{ required: true, message: '请选择区域', trigger: 'change' }],
        goods: [{ required: true, message: '请输入商品', trigger: 'blur' }],
        workorderId: [{ required: true, message: '请输入工单ID', trigger: 'blur' }],
        workorderType: [{ required: true, message: '请输入工单类型', trigger: 'blur' }],
        workorderState: [{ required: true, message: '请选择工单状态', trigger: 'change' }]
      }
    };
  },
  created() {
    this.fetchOperations();
    this.fetchCustomers();
    this.fetchAreas();
  },
  methods: {
    fetchOperations() {
      axios.get('http://localhost:8081/api/operation/getall')
          .then(response => {
            this.operations = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the operations!", error);
          });
    },
    fetchCustomers() {
      axios.get('http://localhost:8081/api/operation/customers')
          .then(response => {
            this.customers = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the customers!", error);
          });
    },
    fetchAreas() {
      axios.get('http://localhost:8081/api/operation/areas')
          .then(response => {
            this.areas = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the areas!", error);
          });
    },
    searchOperations() {
      axios.get(`http://localhost:8081/api/operation/get/${this.searchQuery}`)
          .then(response => {
            this.operations = response.data;
          })
          .catch(error => {
            console.error("There was an error searching the operations!", error);
          });
    },
    openDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetOperation();
    },
    editOperation(operation) {
      this.isEdit = true;
      this.dialogVisible = true;
      this.newOperation = { ...operation };
    },
    addOrUpdateOperation() {
      this.$refs.operationForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            axios.put('http://localhost:8081/api/operation/update', this.newOperation)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchOperations();
                  this.resetOperation();
                  ElMessage.success('业务更新成功');
                })
                .catch(error => {
                  console.error("There was an error updating the operation!", error);
                  ElMessage.error('业务更新失败');
                });
          } else {
            axios.post('http://localhost:8081/api/operation/add', this.newOperation)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchOperations();
                  this.resetOperation();
                  ElMessage.success('业务添加成功');
                })
                .catch(error => {
                  console.error("There was an error adding the operation!", error);
                  ElMessage.error('业务添加失败');
                });
          }
        }
      });
    },
    deleteOperation(id) {
      axios.delete(`http://localhost:8081/api/operation/delete/${id}`)
          .then(() => {
            this.fetchOperations();
            ElMessage.success('业务删除成功');
          })
          .catch(error => {
            console.error("There was an error deleting the operation!", error);
            ElMessage.error('业务删除失败');
          });
    },
    resetOperation() {
      const username = localStorage.getItem('username');
      this.newOperation = {
        customerName: '',
        name: '',
        state: '',
        area: '',
        goods: '',
        workorderId: '',
        workorderType: '',
        workorderReceiveDate: '',
        workorderReturnDate: '',
        workorderState: '',
        fillDate: '',
        operator: username || '',
        dataState: ''
      };
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
